const { execSync } = require("child_process")
const path = require("path")
const { globSync } = require("glob")
const { existsSync, mkdirSync } = require("fs")

const protoDir = "./src/proto"
const protoOut = "./pb"

const plugins = [
    {
        name: "es",
        path: "node_modules/.bin/protoc-gen-es",
        opt: "target=ts"
    }
]

function buildProtoc() {
    if (!existsSync(protoOut)) {
        mkdirSync(protoOut, { recursive: true })
    }

    let cmd = `protoc -I ${protoDir}`;
    const files = globSync(path.join(protoDir, "**/*.proto"), {
        windowsPathsNoEscape: true
    }).map(f => path.relative(process.cwd(), f)).join(" ")

    if (!files) {
        console.log("No .proto files found in", protoDir)
        return null
    }

    plugins.forEach(plugin => {
        cmd += ` --plugin=${plugin.name}=${plugin.path}`;
        cmd += ` --${plugin.name}_out=${protoOut}`;
        if (plugin.opt) {
            cmd += ` --${plugin.name}_opt=${plugin.opt}`
        }
    })
    cmd += ` ${files}`
    return cmd
}

try {
    const cmd = buildProtoc()
    if (cmd) {
        console.log("Compiling proto files...")
        execSync(cmd, { stdio: "inherit" })
        console.log("Proto compilation completed successfully!")
    }
} catch (err) {
    console.error("Proto compilation failed:", err.message)
    process.exit(1)
}
